<template>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="!form.id ? $t('add') : $t('update')"
    :visible.sync="visible"
    width="50vw"
  >
    <el-form
      :model="form"
      :rules="dataRule"
      label-width="100px"
      ref="dataForm"
      v-loading="loading"
    >
      <el-form-item
        label="标题"
        prop="collectionName">
        <el-input
          placeholder="请输入标题（6-30字)"
          v-model="form.collectionName"
        />
      </el-form-item>

      <el-form-item
        label="摘要介绍"
        prop="ext">
        <el-input
          placeholder="请输入描述（10-200字)"
          rows="5"
          size="medium"
          type="textarea"
          v-model="form.ext"
        />
      </el-form-item>
      <el-form-item
        label="字体颜色"
        prop="textColor">
        <el-input
          placeholder="请输入字体颜色Hex值"
          rows="5"
          v-model="form.textColor"
        />
      </el-form-item>

      <el-form-item
        label="首页主图"
        prop="smallUrl">
        <el-upload
          :file-list="mainImgFileList"
          :limit="1"
          :multiple="false"
          :on-exceed="handleImgFileExceed"
          :on-preview="onMainImgPreview"
          :on-remove="onMainImgRemoved"
          :on-success="onMainImgUploadSuccess"
          accept="image/png, image/jpeg"
          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"
          list-type="picture-card"
        >
          <i class="el-icon-plus"/>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="详情背景图"
        prop="url">
        <el-upload
          :file-list="detailImgFileList"
          :limit="1"
          :on-exceed="handleImgFileExceed"
          :on-preview="onDetailImgPreview"
          :on-remove="onDetailImgRemoved"
          :on-success="onDetailImgUploadSuccess"
          accept="image/png, image/jpeg"
          action="http://47.106.93.196:8200/cloud-menu/midea/menu/file/upload"
          list-type="picture-card"
        >
          <i class="el-icon-plus"/>
        </el-upload>
      </el-form-item>

      <el-form-item
        label="型号SN8"
        prop="sn8">
        <sn8-select
          :sn8.sync="form.sn8"
          @change="getDataList"/>

          <!--        <el-select-->
          <!--          @change="getDataList()"-->
          <!--          clearable-->
          <!--          placeholder="型号SN8"-->
          <!--          v-model="form.sn8"-->
          <!--          filterable-->
          <!--        >-->
          <!--          <el-option-->
          <!--            :key="item.value"-->
          <!--            :label="item.label"-->
          <!--            :value="item.value"-->
          <!--            v-for="item in sn8List"-->
          <!--          >-->
          <!--          </el-option>-->
          <!--        </el-select>-->
      </el-form-item>
      <!--      编辑时方可选择菜谱-->

      <el-form-item
        label="菜谱精选"
        v-if="form.id && form.id.length > 0">
        <div class="selected-recipes">
          <span
            :key="item.id"
            class="selected-recipe-item"
            v-for="item in recipes"
          ><el-tag
            @close="clickOnCloseRecipe(item)"
            closable>{{
              item.name
            }}</el-tag></span
            >

          <el-button
            @click="clickOnSelectRecipe()"
            size="small">
            <i class="el-icon-plus"/>
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <template
      slot="footer"
      v-if="!loading">
      <el-button
        :loading="requesting"
        @click="visible = false">{{
          $t("cancel")
        }}</el-button>
      <el-button
        :loading="requesting"
        @click="submit()"
        type="primary"
      >{{ $t("confirm") }}
      </el-button>
    </template>

    <collection-recipe-select
      @onCollectionRecipesSelected="onCollectionRecipesSelected"
      ref="recipeSelect"
      v-if="recipeSelectVisible"
    />

    <el-dialog
      :append-to-body="true"
      :visible.sync="previewDialogVisible">
      <img
        :src="previewImgUrl"
        alt=""
        width="100%" >
    </el-dialog>
  </el-dialog>
</template>

<script>
import mixinViewModule from '@/mixins/mike.view-module'
import CollectionRecipeSelect from './collection-recipe-select'
import remove from 'lodash/remove'
import cloneDeep from 'lodash/cloneDeep'
import Sn8Select from '@/components/sn8.select'

export default {
  name: 'AddOrUpdateCollection',
  mixins: [mixinViewModule],
  components: { Sn8Select, CollectionRecipeSelect },
  data () {
    return {
      previewImgUrl: '',
      previewDialogVisible: false,
      visible: false,
      requesting: false,
      uploadPath: '',
      activatedIsNeed: true,
      recipeSelectVisible: false,
      originalRecipes: [],
      recipes: [],
      loading: false,
      detailImgFileList: [],
      mainImgFileList: [],
      form: {
        collectionName: '',
        ext: '',
        flag: 0,
        id: '',
        smallUrl: '',
        sn8: '',
        sort: 0,
        textColor: '',
        url: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        collectionName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        ext: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        sn8: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        smallUrl: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    visible (newValue, oldValue) {
      this.$refs['dataForm'] && this.$refs['dataForm'].resetFields()
      this.mainImgFileList = []
      this.detailImgFileList = []
      this.recipes = []
    }
  },
  mounted () {
    this.uploadPath = this.mikeNetworkBase + 'midea/menu/file/upload'
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.mainImgFileList = []
        this.detailImgFileList = []

        if (this.form.id) {
          // this.getInfo()
          this.getCollectionInfo()
        }
      })
    },

    /***
     * Network Event
     * */
    getCollectionInfo () {
      if (this.loading) {
        return
      }
      this.loading = true
      this.$http
        .post(
          this.mikeNetworkBase +
            '/midea/menu/collection/content/get/' +
            this.form.id
        )
        .then(({ data: res }) => {
          this.form = res.data
          this.getCollectionRecipes()
          if (this.form.smallUrl && this.form.smallUrl.length > 0) {
            this.mainImgFileList = [
              { name: this.form.smallUrl, url: this.form.smallUrl }
            ]
          }
          if (this.form.url && this.form.url.length > 0) {
            this.detailImgFileList = [
              { name: this.form.url, url: this.form.url }
            ]
          }
          return this.getCollectionRecipes()
        })
        .finally(() => {
          this.loading = false
        })
    },

    getCollectionRecipes () {
      return new Promise(resolve => {
        if (!this.form || !this.form.id || this.form.id.length <= 0) {
          resolve()
          return
        }

        this.$http
          .post(`${this.mikeNetworkBase}/home/midea/menu/collection/menus`, {
            currentPage: 1,
            pageSize: 1000,
            sn8: this.form.sn8,
            collectionId: this.form.id,
            user: {
              userId: 'manager_user'
            }
          })
          .then(({ data: res }) => {
            this.originalRecipes = cloneDeep(res.data)
            this.recipes = cloneDeep(res.data)
            resolve()
          })
      })
    },

    /**
     * Click event
     * */
    clickOnCloseRecipe (item) {
      let recipes = this.recipes
      remove(recipes, recipe => {
        return recipe.id === item.id
      })

      this.$set(this.recipes, recipes)
    },
    clickOnSelectRecipe () {
      this.recipeSelectVisible = true
      this.$nextTick(() => {
        // this.$refs.recipeSelect.dataForm.id = id
        this.$refs.recipeSelect.dataForm.sn8 = this.form.sn8
        this.$refs.recipeSelect.recipes = cloneDeep(this.recipes)
        this.$refs.recipeSelect.init()
      })
    },
    // clickOnDeleteRecipe (item) {
    //   let recipes = this.recipes
    //   remove(recipes, recipe => {
    //     return recipe.id === item.id
    //   })
    //
    //   this.$set(this.recipes, recipes)
    // },

    /**
     * Image Upload Event
     * */
    onDetailImgUploadSuccess (response, file, fileList) {
      if (response.code !== 200) {
        this.form.url = ''
        return
      }
      this.form.url = response.data
    },
    onDetailImgRemoved () {
      this.form.url = ''
    },

    onDetailImgPreview () {
      this.previewImgUrl = this.form.url
      this.previewDialogVisible = true
    },

    onMainImgPreview () {
      this.previewImgUrl = this.form.smallUrl
      this.previewDialogVisible = true
    },
    onMainImgUploadSuccess (response, file, fileList) {
      if (response.code !== 200) {
        this.form.smallUrl = ''
        return
      }
      this.form.smallUrl = response.data
    },
    onMainImgRemoved () {
      this.form.smallUrl = ''
    },
    handleImgFileExceed (files, fileList) {
      this.$message.warning(`只能设置一张图片哦`)
    },

    onCollectionRecipesSelected (recipes) {
      this.recipes = recipes
    },

    /**
     * Submit
     * */
    submit () {
      if (this.requesting) {
        return
      }

      this.$refs['dataForm'].validate(valid => {
        if (!valid) {
          return false
        }
        this.startRequest()
      })
    },
    startRequest () {
      this.requesting = true

      this.$http
        .post(
          `${this.mikeNetworkBase}midea/menu/collection/content/save`,
          this.form
        )
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }

          // success

          // checking if has selected recipes

          let emptySelection = !this.recipes || this.recipes.length <= 0
          let emptyOriginal =
            !this.originalRecipes || this.originalRecipes.length <= 0

          if (emptySelection && emptyOriginal) {
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false

                this.$emit('refreshDataList')
              }
            })
            return
          }

          // return
          // Step 1  , clear up collection recipes

          let originalMenuIds = this.originalRecipes.map(item => {
            return item.id
          })

          console.log(originalMenuIds)

          let menuId = this.form.id

          if (!menuId || menuId.length <= 0) {
            // brand new-old-user one
            return
          }
          return this.$http.post(
            `${this.mikeNetworkBase}midea/menu/collection/content/collection/del`,
            {
              collectionIds: [menuId],
              menuIds: originalMenuIds
            }
          )

          // connect collection to recipes
        })
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }

          // Step 2 , set back selected recipes
          let menuIds = this.recipes.map(item => {
            return item.id
          })

          // Step 2 , set back selected recipes
          return this.$http.post(
            `${this.mikeNetworkBase}midea/menu/collection/content/collection/set`,
            {
              collectionIds: [this.form.id],
              menuIds: menuIds
            }
          )
        })
        .then(({ data: res }) => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }

          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        })
        .catch(() => {
          this.requesting = false
        })
        .finally(() => {
          this.requesting = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.recipe-select {
  margin-bottom: 15px;
}

.selected-recipes {
  .selected-recipe-item {
    margin-right: 10px;
  }
}
</style>
